/*
 * Created on Mon May 11 11:53:21 CEST 2009
 */
package se.sweco.gpsservice;

import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator, GPSUpdateListener  {
	public static BundleContext bc = null;
	GPSConnect service = null;
	
	/* 
	 * Register our GPSConnection bundle and initialize it, start serial connection to the gps
	*/
	public void start(BundleContext context) throws Exception {
		Activator.bc = context;
		
		System.out.println("Starting GPSConnect..");
		service = new GPSConnect();
		
		Hashtable<String, String> props = new Hashtable<String, String>();
		props.put("description", "Fetch data from tinfows.");
		String[] classNames = {GPSConnect.class.getName(), GPSConnect.class.getName()};
		context.registerService(classNames, service, props);
		
		System.out.println("Running GPSConnect..");
		
		//service.setListener(new gpsTest()); C:\\data.csv
		if (System.getProperty("tinfo.gps.simdata") != null) {
			service.simulateData(System.getProperty("tinfo.gps.simdata"), System.getProperty("tinfo.gps.vehicleId"), 2000);
		} else {
			service.connect(System.getProperty("tinfo.gps.comport"), 
					Integer.parseInt(System.getProperty("tinfo.gps.baudrate")));
		}
	}

	/*
	 * Shutdown the serial connection with the GPS unit and clear all buffers.
	 */
	public void stop(BundleContext context) throws Exception {
		System.out.println("Stopping GPSConnect..");
		if(service != null) {
			service.cleanUp();
		}
		Activator.bc = null;
	}
	
	public void GPSUpdateEvent(GPSUpdateEvent e) {
		if(e.getEventType() == GPSUpdateEvent.LOCATION_UPDATE || 
		   e.getEventType() == GPSUpdateEvent.LOC_AND_SAT_UPDATE) {
			System.out.println("Location: Lat: " + e.getSource().getLatitude() + " " + e.getSource().getLatitudeType());
			System.out.println("Location: Long: " + e.getSource().getLongitude() + " " + e.getSource().getLongitudeType());
			System.out.println("Number of sattelites: " + e.getSource().getNumberOfSatellites());
			System.out.println();
		} else if(e.getEventType() == GPSUpdateEvent.VELOCITY_UPDATE) {
			System.out.println("Speed (KM): " + e.getSource().getSpeedKilometer());
			System.out.println();
		} else if(e.getEventType() == GPSUpdateEvent.SATTELITE_UPDATE) {
			System.out.println("Number of sattelites: " + e.getSource().getNumberOfSatellites());
			System.out.println();
		}
	}
}